package com.mrs.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeWithZoneIdSerializer;
import com.mrs.common.HttpEnum;
import com.mrs.common.Result;
import com.mrs.common.dto.UserDto;
import com.mrs.entity.User;
import com.mrs.exception.BusinessException;
import com.mrs.mapper.UserMapper;
import com.mrs.service.UserService;
import com.mrs.utils.TokenUtils;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description: UserController
 * date: 2022/7/13 22:49
 * author: MR.孙
 */
@RestController
@RequestMapping("/user")
public class UserController {

    // @Autowired
    // private UserMapper userMapper;

    @Autowired
    private UserService userService;
    // 新增和修改
    @PostMapping
    public Result<Boolean> save(@RequestBody User user) {
        // 新增或者更新
        return Result.success(userService.saveUser(user));
    }

    // 查询所有数据
    @GetMapping
    public Result<List<User>> index() {
        List<User> all = userService.list();
        return Result.success(all);
    }

    //删除
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
    }

    //批量删除
    @PostMapping("/batch/del")
    public Result<Boolean> delete(@RequestBody List<Integer> ids){
        return Result.success(userService.removeByIds(ids));
    }


    // //分页    @RequestParam  http://localhost:8888/user?currentPage=1&pageSize=2
    // @GetMapping("/page")
    // public Map<String,Object> page(@RequestParam Integer currentPage,
    //                                @RequestParam Integer pageSize,
    //                                @RequestParam String username,
    //                                @RequestParam String email,
    //                                @RequestParam String address){
    //     //当前页=(currentPage-1)*pageSize
    //     currentPage = (currentPage-1)*pageSize;
    //     List<User> pageInfo=userService.page(currentPage,pageSize,username,email,address);
    //     //计算总记录数
    //     List<User> all = userMapper.findAll();
    //     Integer total=all.size();
    //
    //     Map<String,Object> result = new HashMap();
    //     result.put("data",pageInfo);
    //     result.put("total",total);
    //
    //     return result;
    // }


    @GetMapping("/page")
    public Result<Page<User>> page(@RequestParam Integer currentPage,
                                   @RequestParam Integer pageSize,
                                   @RequestParam(defaultValue = "") String username,
                                   @RequestParam(defaultValue = "") String email,
                                   @RequestParam(defaultValue = "") String address){
      Page<User> page = new Page<>(currentPage,pageSize);
      LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.like(!"".equals(username),User::getUsername,username);
      queryWrapper.like(!"".equals(email),User::getEmail,email);
      queryWrapper.like(!"".equals(address),User::getAddress,address);

      return Result.success(userService.page(page, queryWrapper));

    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatarUrl", "头像");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result<Boolean> imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容 但是是手动的不推荐
        // List<List<Object>> list = reader.read(1);
        // List<User> users = CollUtil.newArrayList();
        // for (List<Object> row : list) {
        //     User user = new User();
        //     user.setUsername(row.get(0).toString());
        //     user.setPassword(row.get(1).toString());
        //     user.setNickname(row.get(2).toString());
        //     user.setEmail(row.get(3).toString());
        //     user.setPhone(row.get(4).toString());
        //     user.setAddress(row.get(5).toString());
        //     user.setAvatarUrl(row.get(6).toString());
        //     users.add(user);
        // }

        //解决中文表头问题
        HashMap<String, String> headerAlias = new HashMap<>(6);
        headerAlias.put("用户名", "username");
        headerAlias.put("昵称", "nickname");
        headerAlias.put("邮箱", "email");
        headerAlias.put("电话", "phone");
        headerAlias.put("地址", "address");
        headerAlias.put("头像", "avatarUrl");
        reader.setHeaderAlias(headerAlias);

        List<User> list = reader.readAll(User.class);
        System.out.println(list);
        userService.saveBatch(list);
        return Result.success(true);
    }
    //登录
    @PostMapping("/login")
    public Result<UserDto> login(@RequestBody UserDto userDto) throws BusinessException {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.fail(HttpEnum.Code.ARGS_ERROR,"参数错误");
        }
        return Result.success(userService.login(userDto));
    }

    //注册
    @PostMapping("/register")
    public Result<User> regist(@RequestBody UserDto userDto) throws BusinessException {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.fail(HttpEnum.Code.ARGS_ERROR,"参数错误");
        }
        return Result.success(userService.register(userDto));
    }

    //获取用户信息
    @GetMapping("/username/{username}")
    public Result<User> findOne(@PathVariable String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper));
    }
}
